package br.com.fafica.exemplario.model.dao.array;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import br.com.fafica.exemplario.model.User;
import br.com.fafica.exemplario.model.dao.InterfaceUserDAO;

public class UserDAOArray implements InterfaceUserDAO{
	
	private List<User> banco;
	
	public UserDAOArray() {
		this.banco = new ArrayList<User>();
		this.popularBanco();
	}
	
	public void popularBanco() {
		User user = new User();
		user.setNome("Fulano");
		user.setSenha("123");
		this.insira(user);
		
		user = new User();
		user.setNome("Cicrano");
		user.setSenha("321");
		this.insira(user);
		
		user = new User();
		user.setNome("Beltrano");
		user.setSenha("111");
		this.insira(user);
	}

	@Override
	public void insira(User user) {
		user.setCodigo(this.proximo());
		this.banco.add(user);
	}

	@Override
	public void exclua(User user) {
		User u = this.traga(user);
		if (u != null)
			this.banco.remove(user);
	}

	@Override
	public void altere(User user) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public List<User> listeTodos() {
		ArrayList<User> lista = new ArrayList<User>(banco);
		return lista;
	}
	
	private int proximo() {
		int codigo = 1;
		if (banco.size() != 0) {
			User user = banco.get(banco.size() -1);
			codigo = user.getCodigo();
		}
		return codigo;
	}

	private User traga(User user) {
		Iterator<User> it = banco.iterator();  
		while (it.hasNext()) {  
		   User userBanco = it.next();  
		   if (user.getCodigo() == userBanco.getCodigo()) {  
		      return userBanco;
		   }  
		}
		return null;
	}
}
